#!/usr/bin/env python3
"""Simple Modbus synchronous client example for login records."""

# --------------------------------------------------------------------------- #
# import the various client implementations
# --------------------------------------------------------------------------- #
import pymodbus.client as ModbusClient
from pymodbus import ExceptionResponse, FramerType, ModbusException
import logging

# Configure logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

def run_sync_client(host, port):
    """Run sync client to connect to Modbus Slave and prepare for login records."""
    print("Initializing Modbus TCP client")
    client = ModbusClient.ModbusTcpClient(host, port=port)

    try:
        # Connect to the Modbus Slave
        client.connect()
        print("Connected to Modbus Slave")

        # Here you can add your logic to handle login records
        # For example, you might want to write login records to holding registers
        # For now, we'll just print a message indicating the connection is ready for use
        print("Ready to handle login records")

    except ModbusException as e:
        log.error(f"ModbusException: {e}")
    except Exception as e:
        log.error(f"Unexpected error: {e}")
    finally:
        # Close the connection
        client.close()
        print("Connection closed")

if __name__ == "__main__":
    # Replace '127.0.0.1' and '5020' with the actual IP address and port of your Modbus Slave
    run_sync_client("127.0.0.1", 5020)